package io.gitee.thant.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import io.gitee.thant.entity.Result;

//永远要在调用waitFor()方法之前读取数据流
//永远要先从标准错误流中读取，然后再读取标准输出流
public class ShellUtil {
	public static Result execCommand(String command, String join) {
		if (StringUtil.isEmpty(join)) {
			join = "\r\n"; 
		}
		
		Result rs = new Result();
		Process process = null;
		try {
			process = Runtime.getRuntime().exec(command);
			
			InputStream errstm = process.getErrorStream();
			InputStream inpstm = process.getInputStream();
			InputStreamReader errir = new InputStreamReader(errstm);
			InputStreamReader inpir = new InputStreamReader(inpstm);
			BufferedReader errrd = new BufferedReader(errir);
			BufferedReader inprd = new BufferedReader(inpir);
			StringBuilder errsb = new StringBuilder();
			StringBuilder inpsb = new StringBuilder("cmd=["+command+"]"+join);
			
			process.getOutputStream().close();
			
			String line;
			do {
				if (errstm.available()>0) {
					while ((line = errrd.readLine()) != null) {
						errsb.append(line).append(join);
					}
				}
				if (inpstm.available()>0) {
					while ((line = inprd.readLine()) != null) {
						inpsb.append(line).append(join);
					}
				}
			} while(process.isAlive() || errstm.available()>0 || inpstm.available()>0);
			
			errrd.close();
			inprd.close();
			errir.close();
			inpir.close();
			errstm.close();
			inpstm.close();
			
			if (errsb.length()>0) {
				inpsb.append("错误信息:").append(errsb).append(join);
			}
			int code = process.waitFor();
			inpsb.append("返回值:").append(code);
			
			if (0 == code) {
				rs.setOK(inpsb.toString());
			} else {
				rs.setError(inpsb.toString());
			}
		} catch (Exception e) {
			rs.setError(e);
			if (process != null && process.isAlive()) {
				process.destroy();
				process = null;
			}
		}
		return rs;
	}
}
